import os
import face_recognition

import io
from PIL import Image, ImageFile

from enums import PLATFORM_DIR_PATH
from enums import DIR_ALL_FACEDATA, DIR_ALL_FACEDATA_SOURCE, DIR_ALL_FACEDATA_VERIFY

from tools import log
from tools.utils import Base64ToBytes, GetNowDateTime, GetRandomChar



file = "/Users/software-four/Documents/projectAll/python/mirco-service-grpc/userbe/static/face/testdir/aobama.jpg"

images_dir_path = f"{PLATFORM_DIR_PATH}/{DIR_ALL_FACEDATA}/{DIR_ALL_FACEDATA_SOURCE}"


FACE_ENCODING_LIST = []
LOAD_NAME_LIST = []


def refreshFaceDataFunc():
    log.info("刷新人脸数据")
    global LOAD_NAME_LIST, FACE_ENCODING_LIST
    name_list = []
    file_list = []
    main_path = images_dir_path
    data_list = os.listdir(main_path)

    def deep_dir(path: str):
        result_name_list = []
        result_file_list = []
        cache_data_list = os.listdir(path)
        for cache_item in cache_data_list:
            cache_item_path = f"{path}/{cache_item}"
            if os.path.isdir(cache_item_path):
                result_list = deep_dir(cache_item_path)
                result_name_list += result_list[0]
                result_file_list += result_list[1]
            else:
                result_name_list.append(cache_item)
                result_file_list.append(cache_item_path)
        return [result_name_list, result_file_list]

    for item in data_list:
        item_path = f"{main_path}/{item}"
        if os.path.isdir(item_path):
            result_list = deep_dir(item_path)
            name_list += result_list[0]
            file_list += result_list[1]
        else:
            name_list.append(item)
            file_list.append(item_path)

    load_name_list = []
    load_image_list = []
    for index, item in enumerate(file_list):
        try:
            load_image = face_recognition.load_image_file(item)
            load_name_list.append(name_list[index])
            load_image_list.append(load_image)
        except Exception as e:
            pass

    face_name_list = []
    face_encoding_list = []

    for load_image_index, load_image_item in enumerate(load_image_list):
        try:
            item_face_encoding = face_recognition.face_encodings(load_image_item)[0]
            face_name_list.append(load_name_list[load_image_index])
            face_encoding_list.append(item_face_encoding)
        except Exception as e:
            log.warning(f"load face encoding error: {item}")
            log.warning_none(str(e))
    
    LOAD_NAME_LIST = face_name_list
    FACE_ENCODING_LIST = face_encoding_list


refreshFaceDataFunc()


def check(image_data) -> list[str] | None:
    global LOAD_NAME_LIST, FACE_ENCODING_LIST
    try:
        file_face_encoding = face_recognition.face_encodings(image_data)[0]
    except Exception as e:
        print("被检测的必须是人像图片")
        print(e)
        return None

    results = face_recognition.compare_faces(FACE_ENCODING_LIST, file_face_encoding, tolerance=0.3)

    result_name_list: list[str] = []
    for index, item in enumerate(results):
        if item:
            result_name_list.append(LOAD_NAME_LIST[index])

    format_result_name_list = []
    for ritem in result_name_list:
        name_list = ritem.split(".")
        format_result_name_list.append(".".join(name_list[:-1]))

    return format_result_name_list



def runImageFile(image_path: str):
    image_data = face_recognition.load_image_file(image_path)
    return check(image_data)

def runRGBIO(image_data):
    return check(image_data)

def runBaseImg(basedata: str):
    """
        图片/base64
    """
    basedata_format = basedata.split(",")[-1]
    byte_stream = io.BytesIO(Base64ToBytes(basedata_format))
    image = Image.open(byte_stream)
    file_path = saveImgWithBase64(image)
    image.close()
    byte_stream.close()
    results = runImageFile(file_path)
    log.info("人脸识别结果", results)
    return results

def saveImgWithBase64(image: ImageFile.ImageFile):
    stamp = GetRandomChar(8)
    date_time = GetNowDateTime()
    date_time_list = date_time.split(" ")
    date_list = date_time_list[0].split("-")
    time_list = date_time_list[1].split(":")
    time_str = "".join(time_list)
    dir_path = f"{PLATFORM_DIR_PATH}/{DIR_ALL_FACEDATA}/{DIR_ALL_FACEDATA_VERIFY}/{date_list[0]}{date_list[1]}"
    os.makedirs(dir_path, exist_ok=True)
    path = f"{date_list[2]}-{time_str}"
    img_file = f"{dir_path}/{path}-{stamp}.png"
    image.save(img_file)
    return img_file


